package com.caigou.modules.login.ui

import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.Session
import com.caigou.comm.base.bean.UserBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.DialogUtil
import com.caigou.comm.base.utils.SessionUtil
import com.caigou.modules.login.R
import com.caigou.modules.login.databinding.FragmentRegisterBinding
import com.caigou.modules.login.viewmodel.LoginViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/09/29
 */
@AndroidEntryPoint
class RegisterFragment : BaseFragment(), View.OnClickListener {

    private var _binding: FragmentRegisterBinding? = null
    private val binding get() = _binding!!

    private val loginViewModel: LoginViewModel by viewModels()

    private var isShowText = false

    override val mDialog by lazy {
        DialogUtil.getLoadingDialog(requireActivity(), "注册中...")
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentRegisterBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun onBack() {
        binding.registerEetName.editText.setText("")
        binding.registerEetPwd.editText.setText("")
        binding.registerEetCode.editText.setText("")
    }

    override fun initView() {
        binding.registerEetName.editText.hint = "用户昵称"

        binding.registerEetPwd.run {
            editText.hint = "密码长度6-16位"
            rightImageView.setImageResource(R.drawable.img_login_eye1)
            rightImageView.setOnClickListener {
                if (isShowText) {
                    isShowText = false
                    rightImageView.setImageResource(R.drawable.img_login_eye1)
                    editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
                } else {
                    isShowText = true
                    rightImageView.setImageResource(R.drawable.img_login_eye2)
                    editText.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                }
            }
            editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
        }

        binding.registerEetCode.editText.hint = "请输入邀请码（可以不填）"

        binding.registerBtnRegister.setOnClickListener(this)
    }

    override fun lazyLoad() {
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(loginViewModel.userLiveData, ::handleRegister)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleRegister(status: Resource<UserBean>) {
        when (status) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(status.errorMsg)) {
                    showToast(status.errorMsg)
                } else {
                    showToast("用户登录异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (status.data == null) {
                    return
                }

                val mobile = (requireActivity() as LoginActivity).mobile
                val password = binding.registerEetPwd.editText.text.toString()
                val session = Session(mobile, password)
                SessionUtil.setSession(session)

                AppBackgroundInfo.instance.hasLogin = true
                AppBackgroundInfo.instance.userBean = status.data
                LiveDataBus.get().with(BusKey.LOGIN_SUCCESS).value = Any()
                requireActivity().finish()
            }
        }
    }

    override fun onClick(v: View?) {
        v?.apply {
            if (id == binding.registerBtnRegister.id) {
                val nickName = binding.registerEetName.editText.text.toString()
                val pwd = binding.registerEetPwd.editText.text.toString()
                val code = binding.registerEetCode.editText.text.toString()
                val mobile = (requireActivity() as LoginActivity).mobile
                val smsCode = (requireActivity() as LoginActivity).smsCode

                if (TextUtils.isEmpty(nickName)) {
                    showToast("用户昵称不能为空")
                    return
                }

                if (TextUtils.isEmpty(pwd)) {
                    showToast("密码不能为空")
                    return
                }

                if ((pwd.length < 6) || (pwd.length > 16)) {
                    showToast("请输入6-16位长度密码")
                    return
                }

                loginViewModel.register(nickName, mobile, pwd, smsCode, code)
            }
        }
    }
}